extends Control

# 预加载技能数据库
const SkillDatabase = preload("res://scripts/skills/database/skill_database.gd")

# 技能格子场景
var skill_slot_scene = preload("res://scenes/ui/skill_bar/skill_slot.tscn")

# 记录已添加的技能格子
var skill_slots = {}

# 获取玩家节点和状态
var player
var player_stats

# 获取容器节点
@onready var skill_container = $HBoxContainer
@onready var background_panel = $BackgroundPanel

# UI尺寸参数
var base_slot_size = Vector2(50, 50)  # 基准技能格子尺寸

func _ready():
	print("技能栏初始化")
	
	# 确保初始状态下技能栏是可见的
	visible = true
	background_panel.visible = true
	skill_container.visible = true
	
	# 获取玩家节点
	await get_tree().process_frame  # 等待一帧确保场景完全加载
	player = get_tree().get_first_node_in_group("player")
	
	if player:
		print("技能栏：找到玩家节点")
		player_stats = player.get_stats()
		if player_stats:
			print("技能栏：获取到玩家状态信息")
			# 监听技能学习信号
			player_stats.learned_new_skill.connect(_on_learned_new_skill)
			# 初始化已学习的技能
			_update_skill_bar()
		else:
			push_error("技能栏：未能获取玩家状态信息")
	else:
		push_error("技能栏：未找到玩家节点")
		
	# 重置到默认位置
	reset_to_default_position()
	
	# 连接窗口尺寸改变的信号
	get_viewport().size_changed.connect(_on_viewport_size_changed)

# 重置到默认位置
func reset_to_default_position():
	# 设置绝对位置而非动态计算
	var viewport_size = get_viewport_rect().size
	
	# 背景面板默认尺寸和位置
	background_panel.size = Vector2(340, 60)
	background_panel.position = Vector2(viewport_size.x / 2 - 170, viewport_size.y - 70)
	
	# 技能容器默认位置
	skill_container.position = Vector2(viewport_size.x / 2 - 150, viewport_size.y - 65)
	skill_container.size = Vector2(300, 50)
	
	print("技能栏位置重置: ", background_panel.position)

# 更新技能栏，显示所有已学习的技能
func _update_skill_bar():
	print("更新技能栏")
	
	# 先清空现有技能格子
	for slot in skill_slots.values():
		if is_instance_valid(slot):
			slot.queue_free()
	skill_slots.clear()
	
	# 获取已学习的技能
	var learned_skills = player_stats.skills if player_stats else []
	
	# 模拟技能（临时调试用）
	if learned_skills.size() == 0:
		learned_skills = ["sword_wave", "quick_slash"]
		print("添加测试技能：", learned_skills)
	
	# 添加已学习的技能到技能栏
	var slot_count = 0
	for skill_id in learned_skills:
		# 只显示有快捷键绑定的技能
		if SkillDatabase.skill_data.has(skill_id) and SkillDatabase.skill_data[skill_id].has("key_bind"):
			var skill_info = SkillDatabase.skill_data[skill_id]
			
			# 实例化技能格子
			var skill_slot = skill_slot_scene.instantiate()
			skill_container.add_child(skill_slot)
			
			# 配置技能信息
			skill_slot.setup(skill_id, skill_info["name"], skill_info["key_bind"], skill_info["icon"])
			
			# 增加引用
			skill_slots[skill_id] = skill_slot
			
			# 连接冷却时间更新，确保每个技能只使用自己的冷却函数
			_connect_skill_cooldown(skill_slot, skill_id)
			
			slot_count += 1
	
	print("技能栏已更新，显示" + str(slot_count) + "个技能")
	
	# 确保技能栏显示在界面上
	visible = true
	background_panel.visible = true
	skill_container.visible = true

# 连接所有技能的冷却时间
func _connect_skill_cooldown(skill_slot, skill_id: String):
	# 清除任何现有的更新函数，确保不会混合多个冷却
	skill_slot.update_cooldown_func = null
	
	# 根据技能ID分配特定的冷却函数
	match skill_id:
		"sword_wave":
			if player and player.has_method("get_sword_wave_cooldown_percent"):
				skill_slot.skill_id = skill_id  # 确保技能槽知道自己的ID
				skill_slot.update_cooldown_func = func(): 
					if player and is_instance_valid(player):
						return player.get_sword_wave_cooldown_percent()
					return 0.0
		"quick_slash":
			if player and player.has_method("get_quick_slash_cooldown_percent"):
				skill_slot.skill_id = skill_id  # 确保技能槽知道自己的ID
				skill_slot.update_cooldown_func = func(): 
					if player and is_instance_valid(player):
						return player.get_quick_slash_cooldown_percent()
					return 0.0
		_:
			# 对于其他技能，默认无冷却
			skill_slot.skill_id = skill_id  # 确保技能槽知道自己的ID
			skill_slot.update_cooldown_func = func(): return 0.0
			
	print("技能 ", skill_id, " 冷却显示已连接")
	
	# 确保每个技能格子有唯一的材质
	await get_tree().process_frame
	if skill_slot.has_method("_ensure_unique_material"):
		skill_slot._ensure_unique_material()

# 当学习新技能时更新技能栏
func _on_learned_new_skill():
	_update_skill_bar()

# 当视口大小改变时重置位置
func _on_viewport_size_changed():
	reset_to_default_position() 
